<!-- 坐席工作报表 -->
<template>
	<a-card>
		<a-form border="false" ref="searchFormRef" :model="searchFormState" :rules="searchFormRules">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="创建日期" name="beginTime">
						<a-date-picker
							v-model:value="searchFormState.beginTime"
							value-format="YYYY-MM-DD"
							placeholder="请选择创建日期"
							style="width: 100%"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="所属公司" name="deptId">
						<a-tree-select
							v-model:value="searchFormState.deptId"
							class="xn-wd"
							:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
							placeholder="请选择组织"
							allow-clear
							tree-default-expand-all
							:tree-data="treeData"
							:tree-default-expanded-keys="treeDefaultExpandedKeys"
							:field-names="{
								children: 'children',
								label: 'name',
								value: 'id'
							}"
							@change="deptChange"
						></a-tree-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="所属团队" name="directorId">
						<a-select
							v-model:value="searchFormState.directorId"
							placeholder="请选择所属团队"
							:options="managerByOrgIdList"
							allowClear
							:field-names="{
								label: 'name',
								value: 'id'
							}"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="pageList(1)">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
	<a-card :bordered="false" class="mt-2">
		<a-row :gutter="24" class="mb-5">
			<a-col :span="2">
				<a-button type="primary" @click="toExport">导出</a-button>
			</a-col>
		</a-row>
		<a-table
			ref="tableRef"
			:columns="columns"
			:data-source="dataSource"
			bordered
			:row-key="(record) => record.id"
			:scroll="{ x: 'max-content' }"
			:pagination="pagination"
			@change="handleTableChange"
		>
			<template v-if="column.dataIndex === 'manager'">
				<a-space>{{ managerName }}</a-space>
			</template>
		</a-table>
	</a-card>
</template>

<script setup name="callReport">
	import callReceiptApi from '@/api/tjzy/call/receipt/callReceiptApi'
	import dayjs from 'dayjs'
	import bizUserApi from '@/api/biz/bizUserApi'
	import downloadUtil from '@/utils/downloadUtil'
	import { message } from 'ant-design-vue'
	import userApi from '@/api/sys/userApi'

	const pagination = ref({
		current: 1, // 当前页码
		pageSize: 10, // 每页条数
		total: 0, // 数据总量
		showSizeChanger: true, // 是否可以改变每页数量
		pageSizeOptions: ['10', '20', '50', '100'],
		showQuickJumper: true,
		showTotal: (total, range) => {
			return `${range[0]}-${range[1]} 共 ${total} 条 `
		}
	})
	const searchFormRef = ref()
	const tableRef = ref()
	const searchFormState = ref({
		current: pagination.value.current,
		size: pagination.value.pageSize,
		beginTime: dayjs().startOf('day').format('YYYY-MM-DD'),
		deptId: undefined,
		directorId: undefined
	})
	const managerByOrgIdList = ref([]) //组织对应主管列表
	const managerName = ref('') //表单选中主管名字
	const searchFormRules = ref({
		deptId: [
			{
				required: true,
				message: '请选择所属公司',
				trigger: 'change'
			}
		],
		beginTime: [
			{
				required: true,
				message: '请选择创建日期',
				trigger: 'change'
			}
		]
	})
	const treeData = ref([])
	const treeDefaultExpandedKeys = ref([])
	const dataSource = ref([])
	const columns = [
		{
			title: '员工姓名',
			dataIndex: 'userName'
		},
		{
			title: '所属团队',
			dataIndex: 'manager'
		},
		{
			title: '拨打情况(接通/总拨打数)',
			width: '300px',
			dataIndex: 'info'
		},
		{
			title: '接通率',
			dataIndex: 'connRate'
		},
		{
			title: '通话时长(单位：秒)',
			dataIndex: 'callDuration'
		},
		{
			title: '拒绝沟通用户数(时长<15s)',
			dataIndex: 'noValidConnected'
		},
		{
			title: '坐席沟通能力接通率(吸引用户不挂机)',
			dataIndex: 'validConnectRate'
		},
		{
			title: '有效通话时长(单位：秒)',
			dataIndex: 'validCallDuration'
		},
		{
			title: '部门名称',
			dataIndex: 'deptName'
		}
	]
	const handleTableChange = (pagination, filters, sorter) => {
		if (!(searchFormState.value.current === pagination.current && searchFormState.value.size === pagination.pageSize)) {
			searchFormState.value.size = pagination.pageSize
			pageList(pagination.current)
		}
	}
	const pageList = (current) => {
		// console.log('searchFormState',searchFormState);

		searchFormRef.value
			.validate()
			.then((res) => {
				if (res) {
					searchFormState.value.current = current
					callReceiptApi.pageListReport(searchFormState.value).then((res) => {
						dataSource.value = res.records
						pagination.value.total = res.total
						pagination.value.current = res.current
						pagination.value.pageSize = res.size
						managerChange(searchFormState.value.directorId)
					})
				}
			})
			.catch((err) => {
				message.error('表单校验失败，请重新核对表单')
			})
	}
	// 重置
	const reset = () => {
		searchFormRef.value.resetFields()
		searchFormState.value.deptId = treeData.value[0].id
		deptChange(searchFormState.value.deptId)
		pageList(1)
	}
	const toExport = () => {
		callReceiptApi.exportReport(searchFormState.value).then((res) => {
			downloadUtil.resultDownload(res)
		})
	}
	// 所属公司选项变化
	const deptChange = (value) => {
		if (value) {
			userApi.getManagerByOrgId(value).then((res) => {
				managerByOrgIdList.value = res
				searchFormState.value.directorId = undefined
			})
		} else {
			managerByOrgIdList.value = []
			searchFormState.value.directorId = undefined
			managerName.value = ''
		}
	}
	// 所属团队选项变化
	const managerChange = (value) => {
		if (value) {
			managerName.value =
				managerByOrgIdList.value.filter((item) => {
					return item.id === value
				})[0].name + '团队'
		} else {
			managerName.value = ''
		}
	}
	onMounted(() => {
		bizUserApi.userOrgTreeSelector().then((res) => {
			if (res !== null) {
				treeData.value = res
				// 默认展开2级
				treeData.value.forEach((item) => {
					// 因为0的顶级
					if (item.parentId === '0') {
						treeDefaultExpandedKeys.value.push(item.id)
						// 取到下级ID
						if (item.children) {
							item.children.forEach((items) => {
								treeDefaultExpandedKeys.value.push(items.id)
							})
						}
					}
				})
				searchFormState.value.deptId = treeData.value[0].id
				deptChange(searchFormState.value.deptId)
			}
		})
	})
</script>
